#include<stdio.h>
#include<unistd.h>
#include<string.h>

/*
 *
ret = 4
read str: abcd
ret = 4
read str: efgh
ret = 4
read str: abcd
ret = 4
read str: efgh
ret = 4
read str: abcd
ret = 4
read str: efgh
ret = 4
read str: efghabcd
ret = 8
read str: abcdefgh
ret = 8
read str: abcdefgh

 *
 */

int main(){
	int fd[2];
	int ret;
	int i;
	pid_t pid;
	char buf[10] = {0};
	ret = pipe(fd);

	//创建两个平行子线程
	for(i = 0; i < 2; i++){
		pid = fork();
		if(pid < 0){
			perror("fork");
			return -1;
		}else if(pid == 0){
			//子线程
			break;
		}else{
			//父线程
		}
	}
	//父线程 读
	if(i == 2){
		close(fd[1]);
		while(1){
			//不加下面的if判断，程序也没有出错，说明read是阻塞等待的
			memset(buf, 0, 10);
			ret = read(fd[0], buf, 10);
			printf("ret = %d\n", ret);
			//if(ret > 0){
				printf("read str: %s\n", buf);
			//}
		}
		return 0;
	}
	//子线程1  写
	if(i == 1){
		close(fd[0]);
		while(1){
			strcpy(buf, "abcd");
			write(fd[1], buf, strlen(buf));
			sleep(1);
		}
		return 0;
	}
	//子线程2 写
	if(i == 0){
		close(fd[0]);
		while(1){
			strcpy(buf, "efgh");
			write(fd[1], buf, strlen(buf));
			sleep(1);
		}
		return 0;
	}
}
